/**
 * @file face_detection and face_landmark_localization model
 */

import { Runner } from '@paddlejs/paddlejs-core';
import '@paddlejs/paddlejs-backend-webgl';

let detectionRunner = null as Runner;
let landmarkRunner = null as Runner;

export async function init(){
    detectionRunner = new Runner({
        modelPath: '/models/face_detection_output',
        modelName: 'blazeface_1000e',
        feedShape: { // 模型输入图片宽高为640
            fw: 640, // 宽
            fh: 640 // 高
        },
        // mean和std通过模型获得
        mean: [123, 117, 104],
        std: [127.502231, 127.502231, 127.502231],
        fill: '#fff'


    });

    landmarkRunner = new Runner({
        modelPath: '/models/face_landmark_output',
        modelName: 'Face_landmark',
        feedShape: {
            "fc": 1, 
            "fh": 60, 
            "fw": 60
        }, 
        fill: '#fff'
    });


    await detectionRunner.init();
    await landmarkRunner.init();
}

export async function detect(image){
    const output = await detectionRunner.predict(image);
    // 输出结果阈值
    const thresh = 0.5;
    // output返回识别框，将其通过demo中的ts操作放入到html中
    return output.filter(item => item[1] > thresh);
}

export async function keyPointDetection(image){
    const output = await landmarkRunner.predict(image);
    return output;
}


// 创建图像
export function createImage(imgPath: string): Promise<HTMLImageElement> {
    return new Promise(resolve => {
        const image = new Image();
        image.crossOrigin = 'anonymous';
        image.onload = () => {
            resolve(image);
        };
        image.src = imgPath;
    });
}